package com.flycms.web.front.rest;

import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PagingParam;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.comment.model.Collects;
import com.flycms.module.comment.model.FlyContentType;
import com.flycms.module.comment.model.OptionCount;
import com.flycms.module.comment.service.CollectsService;
import com.flycms.module.message.service.MessageService;

/**
 *
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年2月22日
 * @Date 2020年2月22日
 */

@RestController
@RequestMapping("/ct")
public class CollectController extends BaseController {

    private static final Logger logger = LogManager.getLogger(CollectController.class);
    
    @Autowired
    protected CollectsService collectsService;
    
    @Autowired
    protected MessageService messageService;
    
    /**
     * 对某个内容进行收藏
     * @param contentType
     * @param contentId
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/u/add/{contentType}/{contentId}"})
    public RestDataVo addCollect(@PathVariable("contentType") String contentType,
            @PathVariable("contentId") Long contentId) {
        RestDataVo rest = new RestDataVo();
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("收藏失败，请检查传入参数，{0}:{1}", contentType, contentId + "");
        }
        Long userId = getUserId();
        try {
            Collects col = collectsService.queryCollectedCollect(userId, contentId, ct);
            if (col != null) {
                return RestDataVo.ERROR("收藏失败，重复收藏");
            }
            Object obj = collectsService.queryContentObject(contentId, ct);
            if (obj == null) {
                return RestDataVo.ERROR("收藏失败，收藏内容不存在");
            }
            Collects collect = new Collects();
            collect.setContentId(contentId);
            collect.setUserId(userId);
            collect.setCreateTime(new Date());
            OptionCount o = collectsService.addCollect(collect, ct);
            rest = RestDataVo.OK(o);
            try {
                messageService.addSystemMessage(userId, CommonUtils.getOwner(obj).getUserId(), ct.msg(),
                        CommonUtils.getCollerctMessageModel(CommonUtils.getOwner(obj).getUserName(), ct.msg()));
            } catch (Exception e) {
                
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("收藏失败");
        }
        
        return rest;
    }
    
    /**
     * 取消收藏
     * @param id
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/u/remove/{contentType}/{id}"})
    public RestDataVo removeCollect(@PathVariable("contentType") String contentType,
            @PathVariable("id") Long id) {
        RestDataVo rest = new RestDataVo();
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("获取收藏失败，请检查传入参数");
        }
        Long userId = getUserId();
        try {
//            Collects c = collectsService.queryCollectById(userId, id, ct);
//            if (c == null) {
//                return RestDataVo.ERROR("取消收藏失败，收藏不存在");
//            }
            Collects c = new Collects();
            c.setContentId(id);
            c.setUserId(userId);
            
            OptionCount o = collectsService.removeCollect(c, ct);
            rest = RestDataVo.OK(o);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("取消收藏失败");
        }
        return rest;
    }
    
    /**
     * 获取某个内容的收藏列表
     * @param contentType
     * @param contentId
     * @param paging
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/u/list/{contentType}/{contentId}"})
    public RestDataVo getCollectList(@PathVariable("contentType") String contentType,
            @PathVariable(value = "contentId", required = false) Long contentId,
            @RequestBody(required = false) PagingParam paging) {
        RestDataVo rest = new RestDataVo();
        paging = CommonUtils.validPageParam(paging);
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("获取收藏失败，请检查传入参数，{0}:{1}", contentType, contentId + "");
        }
        Long userId = getUserId();
        try {
            List<Collects> collectList = collectsService.getCollectList(userId, contentId, paging.getOrderBy(),
                        paging.getOrder(), paging.getOffset(), paging.getRows(), ct);
            int count = collectsService.getCollectCount(userId, contentId, ct);
            rest = RestDataVo.PAGE(collectList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取收藏失败");
        }
        return rest;
    }
    
    /**
     * 获取当前用户的收藏列表
     * @param contentType
     * @param paging
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/u/self/list/{contentType}"})
    public RestDataVo getCollectList(@PathVariable(value = "contentType", required = false) String contentType,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("获取收藏失败，请检查传入参数，{0}", contentType);
        }
        Long userId = getUserId();
        try {
            List<Collects> collectList = collectsService.getCollectList(userId, null, paging.getOrderBy(),
                    paging.getOrder(), paging.getOffset(), paging.getRows(), ct);
            int count = collectsService.getCollectCount(userId, null, ct);
            rest = RestDataVo.PAGE(collectList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取收藏失败");
        }
        return rest;
    }
    
    @GetMapping(value = {"/other/list/{contentType}"})
    public RestDataVo getOtherList(@PathVariable(value = "contentType", required = false) String contentType,
            @RequestParam("userId") Long userId,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("获取收藏失败，请检查传入参数，{0}", contentType);
        }
        if (userId == null) {
            return RestDataVo.ERROR("未传入用户ID");
        }
//        Long userId = getUserId();
        try {
            List<Collects> collectList = collectsService.getCollectList(userId, null, paging.getOrderBy(),
                    paging.getOrder(), paging.getOffset(), paging.getRows(), ct);
            int count = collectsService.getCollectCount(userId, null, ct);
            rest = RestDataVo.PAGE(collectList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取收藏失败");
        }
        return rest;
    }
    
    /**
     * 获取某个收藏内容的详情
     * @param contentType
     * @param contentId
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/u/info/{contentType}/{contentId}"})
    public RestDataVo queryCollect(@PathVariable("contentType") String contentType,
            @PathVariable("contentId") Long contentId) {
        RestDataVo rest = new RestDataVo();
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("获取收藏详情失败，请检查传入参数，{0}:{1}", contentType, contentId + "");
        }
        try {
            Object obj = collectsService.queryContentObject(contentId, ct);
            rest = RestDataVo.OK(obj);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取收藏详情失败");
        }
        return rest;
    }
    
}
